﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Arch.Samples.RiaServices.Controls;
using Arch.Samples.RiaServices.Infrastructure;

namespace Arch.Samples.RiaServices.Commands
{
    public class AddCommand<TViewModel, TEntity, TForm> : CollectionViewModelCommand<TViewModel, TEntity>
        where TViewModel : CollectionViewModelBase<TEntity>
        where TEntity : Entity, new()
        where TForm : new()
    {
        public AddCommand(TViewModel viewModel) : base(viewModel) { }

        public AddCommand(TViewModel viewModel, Action<TEntity> addedAction) : this(viewModel)
        {
            AddedAction = addedAction;
        }

        public AddCommand(TViewModel viewModel, Action<TEntity> addedAction, Action<TEntity> canceledAction) : this(viewModel, addedAction)
        {
            CanceledAction = canceledAction;
        }

        public Action<TEntity> AddedAction { get; set; }
        public Action<TEntity> CanceledAction { get; set; }

        public override void Execute(object parameter)
        {
            var entity = new TEntity();
            (entity as IEditableObject).BeginEdit();
            Form form = Form.Create(entity, ViewModel, new TForm());
            form.Closed += FormClosed;
            form.Closing += FormClosing;
            form.Show();
        }

        protected virtual void FormClosing(object sender, CancelEventArgs e)
        {
            var form = (Form)sender;
            var entity = (TEntity)form.CurrentItem;
            (entity as IEditableObject).EndEdit();

            if (form.DialogResult.HasValue && form.DialogResult.Value)
            {
                if (entity.ValidationErrors.Any())
                {
                    (entity as IEditableObject).BeginEdit();
                    e.Cancel = true;
                }
            }
        }


        protected virtual void FormClosed(object sender, EventArgs e)
        {
            var form = (Form)sender;
            var entity = (TEntity)form.CurrentItem;

            if (form.DialogResult.HasValue && form.DialogResult.Value)
            {
                Added(entity);
            }
            else
            {
                Canceled(entity);
            }
        }

        protected virtual void Added(TEntity entity)
        {
            ViewModel.Items.Add(entity);
            if (AddedAction != null) AddedAction(entity);
        }

        protected virtual void Canceled(TEntity entity)
        {
            if (CanceledAction != null) CanceledAction(entity);
        }
    }
}
